//
// Created by Kan Zheng on 14/05/2017.
//

#include <iostream>
#include <fstream>
#include "Classpath.h"
#include "CompositeEntry.h"

using namespace std;

void Classpath::parseBootAndExtClasspath(string jreOption) {
    string jreBaseDir = getJreDir(jreOption);
    string jreDir = jreBaseDir;
    jreDir.append("\\lib\\*");
    bootClasspath = newWildcardEntry(jreDir);

    string jreExtDir = jreBaseDir;
    jreExtDir.append("\\lib\\ext\\*");
    extClasspath = newWildcardEntry(jreExtDir);
}

void Classpath::parseUserClasspath(string cpOption) {
}

string getJreDir(string jreOption) {
    fstream _file;
    _file.open(jreOption, ios::in);
    if (jreOption != "" && exists(jreOption)) {
        return jreOption;
    }

    if (exists("./jre")) {
        return "./jre";
    }
}

bool exists(string file_path) {
    fstream _file;
    _file.open(file_path, ios::in);
    if (_file) {
        return true;
    } else {
        return false;
    }
}

Classpath *parse(string jreOption, string cpOption) {
    Classpath *cp = new Classpath();
    cp->parseBootAndExtClasspath(jreOption);
    cp->parseUserClasspath(cpOption);
    return cp;
}

Entry *newWildcardEntry(string path) {
    string baseDir = path.substr(0, path.length() - 2);
    CompositeEntry *compositeEntry = new CompositeEntry();
    return compositeEntry;
}
